#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import pycurl
import StringIO
import sys
import json


def getURL(ids):
    url = 'http://doi.org/api/handles/' + ids
    buf = StringIO.StringIO()
    c = pycurl.Curl()
    c.setopt(pycurl.HTTPGET, 0)
    c.setopt(c.URL, url)
    # c.setopt(pycurl.HTTPPOST, [('db', 'pubmed'), ('id', ids), ('retmode', 'xml')])
    c.setopt(c.WRITEFUNCTION, buf.write)
    c.perform()
    result = buf.getvalue()
    print result
    decoded_result = json.loads(result)
    if decoded_result["responseCode"] == 1:
        print decoded_result["values"][0]["data"]["value"]
    else:
        print "DOI resolve error."
    buf.close()

def getURL2(url):
    buf = StringIO.StringIO()
    c = pycurl.Curl()
    c.setopt(pycurl.HTTPGET, 0)
    c.setopt(c.URL, url)
    # c.setopt(pycurl.HTTPPOST, [('db', 'pubmed'), ('id', ids), ('retmode', 'xml')])
    c.setopt(c.WRITEFUNCTION, buf.write)
    c.perform()
    result = buf.getvalue()
    print result
    buf.close()

def getURL3(url):
    import requests
    r=requests.post(url)
    print r.text


if __name__ == "__main__":
    # getURL(sys.argv[1])
    getURL3("http://www.nature.com/doifinder/10.1038/ng.3586")
